<template>
  <div class="container">
    <!-- 左侧表格 -->
    <div class="box half" v-if="!isViewingResults">
      <el-table :data="isViewingResults ? allStationData : leftTableData" stripe>
        <el-table-column  prop="label" label="项目" align="center" min-width="40" />
        <el-table-column  label="值" align="center">
          <template #default="scope">
            <div v-if="scope.row.id==='number'" class="form-cell">
              <input
                v-model="baseData.number"
                :type="scope.row.inputType"
                :placeholder="scope.row.placeholder"
                class="form-input"
                @focus="saveOriginValue(scope.row.id, baseData.number)"
                @change="handleChange"
              />
            </div>
            <div v-else-if="scope.row.type === 'select' " class="form-cell">
              <select v-model="baseData[scope.row.id]" class="form-select" 
                @focus="saveOriginValue(scope.row.id, baseData[scope.row.id])"
                @change="handleChange"
              >
                <option v-for="option in scope.row.options" :key="option" :value="option">
                  {{ option }}
                </option>
              </select>
            </div>
            <div v-else-if="scope.row.type === 'input'" class="form-cell">
              <input
                v-model="baseData[scope.row.id]"
                :type="scope.row.inputType || 'text'"
                :placeholder="scope.row.placeholder"
                class="form-input"
                @focus="saveOriginValue(scope.row.id, baseData[scope.row.id])"
                @change="handleChange"
                min=1
              />
            </div>
          </template>
        </el-table-column>
      </el-table>
      <el-button class="custom-button" @click="isViewingResults = true">查看结果</el-button>
    </div>
    <!-- 右侧表格 -->
    <div class="box half" v-if="!isViewingResults">
      <el-table :data="isViewingResults ? allStationData : rightTableData" stripe>
        <el-table-column  prop="label" label="项目" align="center" min-width="40" />
        <el-table-column  label="值" align="center">
          <template #default="scope">
            <div v-if="scope.row.id ==='sleepTime' " class="form-cell">
              <div class="demo-time-range">
                <el-time-select
                  v-model="allStationData[baseData.index].startTime"
                  style="width: 15%;min-width: 130px"
                  :max-time="allStationData[baseData.index].endTime"
                  class="mr-4"
                  placeholder="Start time"
                  start="00:00"
                  step="00:10"
                  end="24:00"
                  @focus="saveOriginValue('startTime', allStationData[baseData.index].startTime,'startTime')"
                  @change="handleChangeSleepTime"
                />
                <el-time-select
                  v-model="allStationData[baseData.index].endTime"
                  style="width: 15%;min-width: 130px"
                  :min-time="allStationData[baseData.index].startTime"
                  placeholder="End time"
                  start="00:00"
                  step="00:10"
                  end="24:00"
                  @focus="saveOriginValue('endTime', allStationData[baseData.index].endTime,'endTime')"
                  @change="handleChangeSleepTime"
                />
              </div>
            </div>
            <div v-else-if="scope.row.type === 'input'" class="form-cell">
              <input
                v-model="allStationData[baseData.index][scope.row.id]"
                :type="scope.row.inputType || 'text'"
                :placeholder="scope.row.placeholder"
                class="form-input"
                @focus="saveOriginValue(scope.row.id, allStationData[baseData.index][scope.row.id])"
                @change="handleChange"
              />
            </div>
            <div v-else-if="scope.row.type === 'select' " class="form-cell">
              <select 
                v-model="allStationData[baseData.index][scope.row.id]" 
                class="form-select" 
                @change="handleChange"
                @focus="saveOriginValue(scope.row.id, allStationData[baseData.index][scope.row.id])"
              >
                <option v-for="option in scope.row.options" :key="option" :value="option">
                  {{ option }}
                </option>
              </select>
            </div>
            <div v-else-if="scope.row.type === 'input'" class="form-cell">
              <input
                v-model="allStationData[baseData.index][scope.row.id]"
                :type="scope.row.inputType || 'text'"
                :placeholder="scope.row.placeholder"
                class="form-input"
                @focus="saveOriginValue(scope.row.id, allStationData[baseData.index][scope.row.id])"
                @change="handleChange"
              />
            </div>
            <div v-else-if="scope.row.type === 'switch'" class="form-cell">
              <el-switch 
                v-model="allStationData[baseData.index][scope.row.id]" 
                active-text="开启" 
                inactive-text="关闭" 
                @focus="saveOriginValue(scope.row.id, allStationData[baseData.index][scope.row.id])"
                @change="handleChange(scope.row.id, allStationData[baseData.index][scope.row.id],'switch')"
              />
            </div>
          </template>
        </el-table-column>
      </el-table>
      <el-button class="custom-button" @click="applicationDialogVisible=true">应用此设置</el-button>
    </div>
    <!-- 结果 -->
    <div class="box full" v-if="isViewingResults">
      <el-table :data="allStationData" stripe >
        <el-table-column prop="baseStationNumber" label="基站序号" align="center" />
        <el-table-column prop="transmissionPower" label="发射功率" align="center" />
        <el-table-column prop="bandwidth" label="基站带宽" align="center" />
        <el-table-column prop="startTime" label="休眠开始时间" align="center" />
        <el-table-column prop="endTime" label="休眠结束时间" align="center" />
        <el-table-column prop="antennaStatus" label="天线状态" align="center" />
      </el-table>
      <el-button class="custom-button" @click="isViewingResults = false">修改数据</el-button>
    </div>
    <!-- 确认修改dialog -->
    <el-dialog
      v-model="changeDialogVisible"
      title="是否确定修改数据"
      width="500"
      :before-close="()=>{}"
    >
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="cancelChange">取消</el-button>
          <el-button type="primary" @click="handleSubmit">
            确定
          </el-button>
        </div>
      </template>
    </el-dialog>
    <!-- 一键应用dialog -->
    <el-dialog
      v-model="applicationDialogVisible"
      title="请选择应用范围"
      width="500"
    >
      <div >
        <el-input-number
          v-model="applicationScope.start"
          style="width: 15%;min-width: 130px"
          :max="applicationScope.end"
          min=0
          placeholder="Start"
        >
          <template #prefix>
            <span>from</span>
          </template>
        </el-input-number>
        <el-input-number
          type="number"
          v-model="applicationScope.end"
          style="width: 15%;min-width: 130px"
          :min="applicationScope.start"
          :max="baseData.number"
          placeholder="End"
        >
        <template #prefix>
          <span>to</span>
        </template>
        </el-input-number>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="applicationDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="applySettings">
            确定
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="js" setup>
import { onMounted, reactive, ref } from 'vue'
import {changeSingleStation ,changeStation,changeSettings} from '@/service/api';
import useBaseData from '@/service/baseData';
const baseDataStore = useBaseData()
const changeDialogVisible = ref(false)
const applicationDialogVisible = ref(false)
const isViewingResults = ref(false);
const leftTableData = reactive([
  {
    label: '虚拟基站数调整',
    id:'number',
    type: 'input',
    value: initNumber, // 默认值设为 10
    inputType: 'number',
    placeholder: '请输入基站数',
  },
  {
    label: '虚拟基站序号',
    id:'index',
    type: 'input',
    value: '',
    inputType: 'number',
    placeholder: '请输入虚拟基站序号',
  },
  {
    label: '虚拟基站分布',
    id:'bs_location',
    type: 'select',
    value: '',
    options: [
      '泊松点分布',
      '泊松簇分布',
      '均匀分布'
    ],
    placeholder: '请选择分布方式',
  },
  {
    label: '用户分布',
    id:'user',
    type: 'select',
    value: '',
    options: [
      '泊松点分布',
      '泊松簇分布',
      '均匀分布'
    ],
    placeholder: '请选择用户分布',
  },
  {
    label: '接入方式',
    id:'interface',
    type: 'select',
    value: '',
    options: ['方式1', '方式2', '方式3'],
  },
  {
    label: '碳排放系数调整',
    id:"CO2",
    type: 'input',
    value: '',
    inputType: 'number',
    placeholder: '请输入数值',
  },
  // {
  //   label: '优化算法选择',
  //   id:'algorithm',
  //   type: 'select',
  //   value: '',
  //   options: ['算法A', '算法B', '算法C'],
  // },
]);
const rightTableData = reactive([
  {
    label: '虚拟基站发射功率调整',
    id:'transmissionPower',
    type: 'input',
    value: 20,
    inputType: 'number',
    placeholder: '范围：18-24',
  },
  {
    label: '虚拟基站带宽',
    id:"bandwidth",
    type: 'select', // 改为下拉框
    value: '100M', // 默认值设为 '100M'
    options: ['100M', '80M', '60M', '40M', '30M', '20M'], // 下拉选项
    placeholder: '请选择带宽',
  },
  {
    label: '虚拟基站休眠时间调整',
    id:'sleepTime',
    type: 'input',
    value: '10:30:30-11:50:45',
    placeholder: '',
  },
  {
    label: '虚拟基站天线状态调整',
    id:"antennaStatus",
    type: 'switch',
    value: false,
  },
])
//初始化基站数量
const initNumber = 4
//初始化时单个基站数据，每个基站都一样
const singleStationData = reactive({
  transmissionPower:20,
  bandwidth:'100M',
  startTime:'',
  endTime:'',
  antennaStatus:true,
});
//全部基站的数据
const allStationData = reactive([])
//除基站信息之外的其他数据
const baseData = reactive({
  number:initNumber,
  index:0,
  bs_location:'',
  users:'',
  interface:'',
  CO2:'',
  algorithm:''
})
//批量修改的范围
const applicationScope = reactive({
  start:1,
  end:10
})
//生成结果数据
const initData = () => {
  const numberOfStations = parseInt(baseData.number) || 0; // 获取虚拟基站数调整的值
  // const stationNumber = parseInt(baseData.index) || 0; // 输入的虚拟基站序号
  //清空数据
  allStationData.length = 0
  //进行初始化
  for (var i = 0; i < numberOfStations; i++) {
    allStationData.push({
      baseStationNumber: i,
      transmissionPower: singleStationData.transmissionPower, // 发射功率
      bandwidth: singleStationData.bandwidth, // 带宽
      startTime: singleStationData.startTime, // 休眠时间
      endTime: singleStationData.endTime, // 休眠时间
      antennaStatus: singleStationData.antennaStatus, // 天线状态
    });
  }
  console.log(allStationData)
}
initData()
// 存储原始数据
const originalData  = reactive({
  id:'',
  value:'',
  timeType:''
})

// 保存修改前的数据
const saveOriginValue = (id, value) =>{
  originalData.id = id;
  originalData.value = value;
  console.log('修改前',id,value)
}

//预修改
const handleChange = (id, value,type) =>{
  changeDialogVisible.value = true
  if(type === 'switch'){
    originalData.id = id,
    originalData.value = !value
  }
}
//修改休眠时间
const handleChangeSleepTime = () =>{
  console.log('sleep',)
  if(allStationData[baseData.index].startTime && allStationData[baseData.index].endTime){
    changeDialogVisible.value = true
  }
}
// 取消修改
const cancelChange =() =>{
  //如果修改的是单个基站数据
  if(['transmissionPower','bandwidth','startTime','endTime','antennaStatus'].findIndex((id)=>id===originalData.id)!==-1){
    allStationData[baseData.index][originalData.id]=originalData.value
  }else{
    //修改的是基本数据
    baseData[originalData.id] = originalData.value
  }
  changeDialogVisible.value = false
}
//一键设置功能接口
const quickSetup = (startIndex,endIndex,data) => {
  changeDialogVisible.value = false;
  // 向后端发送数据
  const payload = {
    startIndex,
    endIndex,
    power:data.transmissionPower,
    bandwidth:data.bandwidth,
    start:data.startTime,
    end:data.endTime,
    ststus:data.aantennaStatus
  }
  console.log('批量修改',payload)
  changeStation(payload)
};
// 提交修改数据
const handleSubmit = async () =>{
  let id= originalData.id
  //修改单个基站的设置
  if(['transmissionPower','bandwidth','startTime','endTime','antennaStatus'].findIndex((id)=>id===originalData.id)!==-1){
    let index= baseData.index
    console.log('修改单个基站',allStationData[index])
    changeSingleStation(allStationData[index])
  }
  //修改基础设置
  else{
    //如果是修改基站数目，更新数组
    if(id==='number'){
      applicationScope.end =parseInt(baseData.number)
      const diff = baseData.number - originalData.value
      //如果是增加
      if(diff>0){
        let originLength = originalData.value;
        let newLength = baseData.number;
        for(let i= originLength+1;i<=newLength;i++){
          allStationData.push({
            baseStationNumber: i,
            transmissionPower: singleStationData.transmissionPower, // 发射功率
            bandwidth: singleStationData.bandwidth, // 带宽
            sleepTime: singleStationData.sleepTime, // 休眠时间
            antennaStatus: singleStationData.antennaStatus, // 天线状态
          });
        }
      }
      //如果是减少
      if(diff<0){
        initData()
      }
    }
    changeSettings(baseData)
    console.log('提交数据',baseData)
  }
  changeDialogVisible.value = false
}

const applySettings = () =>{
  const obj = allStationData[baseData.index]
  for(var j= applicationScope.start;j<=applicationScope.end;j++){
    allStationData[j] = Object.assign({},obj,{baseStationNumber:j})
  }
  applicationDialogVisible.value = false
  const start  = applicationScope.start
  const end = applicationScope.end
  quickSetup(start,end,obj)
}

onMounted(()=>{
  baseData.number = baseDataStore.number
  baseData.bs_location = baseDataStore.bs_location
  baseData.users = baseDataStore.users
  baseData.interface = baseDataStore.interface
  baseData.algorithm = baseDataStore.algorithm
})
</script>

<style scoped>
/* 整体容器样式 */
.container {
  display: flex;
  flex-direction: row;
  justify-content: space-around;
  padding: 20px;
  background-color: #f5f5f5; /* 可选背景色 */
  height: 100vh; /* 占满视口高度 */
}

/* 通用白色圆角框样式 */
.box {
  background-color: #fff;
  border-radius: 12px; /* 圆角半径 */
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1); /* 添加阴影 */
  padding: 20px;
  display: flex;
  flex-direction: column;
  justify-content: flex-start;
  align-items: flex-start;
  text-align: left;
  overflow: auto; /* 当内容超出时启用滚动 */
}

.full{
  width:97%;
}
.half{
  width:47%
}

.custom-button {
  background-color: #4CAF50; /* 自定的背景颜色，例如绿色 */
  color: white; /* 按钮文字颜色 */
  margin-top: 15px;
  margin-left: 50%;
  transform: translateX(-50%);
}

/* 表格内单元格样式 */
.form-cell {
  align-items: center;
  display: flex;
  justify-content: center;
  height: 100%;
}

/* 下拉框样式 */
.form-select {
  width: 30%;
  padding: 5px;
  border: 1px solid #ccc;
  border-radius: 5px;
}

/* 输入框样式 */
.form-input {
  width: 30%;
  padding: 5px;
  border: 1px solid #ccc;
  border-radius: 5px;
  font-size: 14px; /* 输入框字体大小 */
  color: #333;
}

/* 占位符字体大小 */
.form-input::placeholder {
  font-size: 12px; /* 调整占位符字体大小 */
  color: #999;
}
</style>
